package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.dto.EmployeeRegisterDTO;
import com.sky.entity.Employee;
import com.sky.exception.*;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;
import java.util.Objects;

@Slf4j
@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;



    /**
     * 员工登录
     *
     * @param employeeLoginDTO 接收到的原始数据
     * @return 登录成功后的员工信息
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // 对前端传过来的明文密码进行md5加密处理
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (Objects.equals(employee.getStatus(), StatusConstant.DISABLE)) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    /**
     * 注册新员工
     *
     * @param employeeLoginDTO 接口接收到的原形
     * @param creatorId 创建员工的 id
     * @return 新增员工
     */
    @Override
    public Employee register(EmployeeRegisterDTO employeeLoginDTO,Long creatorId) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        if(username == null || password == null) {
            throw new AccountOrPasswordIllegalException(MessageConstant.ACCOUNT_OR_PASSWORD_IS_EMPTY);
        }
        Employee byUsername = employeeMapper.getByUsername(username);
        if(byUsername != null) {
            throw  new AccountAlreadyExistException(MessageConstant.ACCOUNT_ALREADY_EXIST);
        }

        Employee employee = Employee.builder()
                .name(employeeLoginDTO.getName())
                .username(employeeLoginDTO.getUsername())
                .password(DigestUtils.md5DigestAsHex(password.getBytes()))
                .sex(employeeLoginDTO.getSex())
                .phone(employeeLoginDTO.getPhone())
//                .idNumber(employeeLoginDTO.getIdNumber())
//                .createTime(LocalDateTime.now())
                .createUser(creatorId).build();

        employeeMapper.insertOne(employee);
        employee.setPassword(password);

        return employee;
    }

    /**
     * 新增员工
     *
     * @param employeeDTO 接收到的原形
     */
    @Override
    public void save(EmployeeDTO employeeDTO) {
//        使用对象属性拷贝
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO, employee);
//        设置账户状态 1为正常 0为不正常
        employee.setStatus(StatusConstant.ENABLE);

//        设置员工的密码，需要使用默认密码
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));

//        设置当前记录的创建时间和修改时间
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
//      从当前线程中获取当前登录用户的id
//        Long currentId = BaseContext.getCurrentId();
//        设置当前记录创建人的id，修改人的id
//        employee.setCreateUser(currentId);
//        employee.setUpdateUser(currentId);

        employeeMapper.insert(employee);
    }

    /**
     * 分页查询员工信息
     *
     * @param employeePageQueryDTO 查询条件
     * @return 分页结果
     */
    @Override
    public PageResult page(EmployeePageQueryDTO employeePageQueryDTO) {

        PageHelper.startPage(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());

        Page<Employee> page = employeeMapper.pageQuery(employeePageQueryDTO);
        long total = page.getTotal();
        List<Employee> records = page.getResult();

        return new PageResult(total, records);
    }

    /**
     * 设置员工的状态
     *
     * @param status 状态
     * @param id 设置的员工id
     */
    @Override
    public void startOrStop(Integer status, Long id) {
//        sql: update employee set status = ? where id = ?
       /* Employee employee = new Employee();
        employee.setStatus(status);
        employee.setId(id);*/
        Employee employee = Employee.builder().status(status).id(id).build();
        employeeMapper.update(employee);
    }

    /**
     * 根据id获取员工信息
     *
     * @param id 员工id
     * @return 员工信息
     */
    @Override
    public Employee getById(Long id) {
        Employee employee = employeeMapper.getById(id);
        employee.setPassword("****");
        return employee;
    }


    /**
     * 修改员工信息
     *
     * @param employeeDTO 接受的实体
     */
    @Override
    public void update(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO, employee);
//        employee.setUpdateTime(LocalDateTime.now());
//        employee.setUpdateUser(BaseContext.getCurrentId());

        employeeMapper.update(employee);
    }


}
